package org.obs.core;

import java.util.List;

import org.obs.core.hibernate.operations.DeleteMessageOperation;
import org.obs.core.hibernate.operations.GetMessagesOperation;
import org.obs.domain.EmailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class MessageSender {

    private HibernateExecutor executor;

    private String smtp;

    public String getSmtp() {
        return smtp;
    }

    public void setSmtp(String smtp) {
        this.smtp = smtp;
    }

    public MessageSender(HibernateExecutor executor) {
        this.executor = executor;
    }

    public void sendAll() {
        List<EmailMessage> messages = executor
                .execute(new GetMessagesOperation());
        for (EmailMessage message : messages) {
            if (sendMessage(message)) {
                executor.execute(new DeleteMessageOperation(message));
            }            
        }
    }
    
    private boolean sendMessage(EmailMessage message) {
        try {
            JavaMailSenderImpl sender = new JavaMailSenderImpl();
            sender.setDefaultEncoding("UTF-8");
            sender.setHost(getSmtp());
            
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom("buddies.org");
            mailMessage.setTo(message.getTo());
            mailMessage.setText(message.getText());
            mailMessage.setSubject(message.getSubject());
            
            sender.send(mailMessage);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
